<?php

/*
 * @description: Контроллер для работы с курсами
 * @copyright Copyright (c) 2012-2017 Marin V. , Tykva A. , Kozel R. , Sokolov D.
 * @version 1.0
 * @link http://lecturebox.ru
 */

class CoursesController extends Model_Controller {

    public function init() {
        /**
         * В parent::init() выполняется создание объекта Zend_Auth - $this->auth
         * и определение id текущего пользователя - $this->user_id
         */
        /*
         *       $session = new Zend_Session_Namespace('lectureBox.l10n');
          if ($session->locale) {
          if($session->locale == 'ru_RU'){

          } else {
          }
          }
         */
        parent::init();
    }

    public function indexAction() {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->title = 'Мои курсы';
                $this->view->headMeta()->appendName('description', 'Курсы лектора');
            } else {
                $this->view->title = 'My Courses';
                $this->view->headMeta()->appendName('description', 'lecturer courses');
            }
        }

        $this->view->headTitle($this->view->title, 'PREPEND');
        $course = new Model_Course();
        $this->view->courses = $course->getCoursesByIdUser($this->user_id);
    }

    /**
     * Вывод по курсам
     * Пример:
     * /courses/cat/view/1/id/1
     *  - страница = 1, тэг id = 1
     */
    public function viewAction() {
        $page = (int) $this->getRequest()->getParam('page', 1);
        $id = (int) $this->getRequest()->getParam('id', 0);
        $errId = (int) $this->getRequest()->getParam('err', 0);
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($errId == 1) {

            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;'>Данная лекция не удовлетворяет правилам сервиса LectureBox (Повтор) и была удалена.</div>";
                } else {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;'>This lecture does not 	
                    comply with the terms of service LectureBox (Repeat) and has been removed</div>";
                }
            }
        }
        if ($errId == 2) {
            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;' >У нас возникли неполадки с сервисом YouTube.</div>";
                } else {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;' >We have problem with the service YouTube.</div>";
                }
            }
        }

        $work = new Model_Lecture();
        $this->view->pages = $work->getPaginatorRows($page, 5, 0, $id);

        if (count($this->view->pages)) {
            foreach ($this->view->pages as $item)
                break;
            $title = htmlspecialchars($item['name']);
            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->title = 'Лекции курса: ' . $title;
                    $this->view->headMeta()->appendName('description', 'Смотреть лекции. Курс ' . $title);
                } else {
                    $this->view->title = 'lectures of course: ' . $title;
                    $this->view->headMeta()->appendName('description', 'Watch lectures. Course ' . $title);
                }
            }
            $this->view->headTitle($title, 'PREPEND');
        }
        $this->view->user_id = $this->user_id;
    }

    /**
     * Вывод по курсам в админке лектора
     * Пример:
     * /courses/cat/view/1/id/1
     *  - страница = 1, тэг id = 1
     */
    public function adminAction() {

        $id = (int) $this->getRequest()->getParam('id', 0);
        $errId = (int) $this->getRequest()->getParam('err', 0);
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($errId == 1) {
            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;'>Данная лекция не удовлетворяет правилам сервиса LectureBox (Повтор) и была удалена.</div>";
                } else {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;'>This lecture does not 	
                        comply with the terms of service LectureBox (Repeat) and has been removed</div>";
                }
            }
        }
        if ($errId == 2) {
            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;' >У нас возникли неполадки с сервисом YouTube.</div>";
                } else {
                    $this->view->error = "<div style='color:red; padding-bottom: 20px;' >We have problem with the service YouTube.</div>";
                }
            }
        }
        $course = new Model_Course();
        $_row = $course->getCoursesById($id);
        //echo $id;

        foreach ($_row as $item) {
            $this->iddd = $item['course_id'];
        }

        if (!isset($this->iddd)) {
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound', 'Error', false, array(null));
        }
        foreach ($_row as $item) {
            if (!isset($item['name'])) {
                $this->getHelper('Redirector')->gotoSimpleAndExit('access', 'Error', false, array(null));
            }

            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->view->title = 'Редактирование лекций курса ' . $item['name'];
                } else {
                    $this->view->title = 'Edit course of lectures ' . $item['name'];
                }
            }
            $this->view->course_id = $item['course_id'];
        }
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->headMeta()->appendName('description', 'Смотреть лекции. Курс');
                $this->view->headTitle('Главная', 'PREPEND');
            } else {
                $this->view->headMeta()->appendName('description', 'Watch lectures. Course');
                $this->view->headTitle('Main Page', 'PREPEND');
            }
        }

        $lecture = new Model_Lecture();
        $this->view->lectures = $lecture->getCourseLectures($id);
        $this->view->cidt = $id;
    }

    /**
     * Добавление курса
     */
    public function addAction() {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->title = 'Добавить новый курс';
                $this->view->headTitle($this->view->title, 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Добавить курсы. Страница добавления курсов.');
            } else {
                $this->view->title = 'Add new course';
                $this->view->headTitle($this->view->title, 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Adding courses page.');
            }
        }


        $form = new Form_AddCourse();

        if ($this->getRequest()->isPost()
                && $form->isValid($this->getRequest()->getPost())) {
            $course = new Model_Course();
            $course->fill($form->getValues());
            $course->user_id = $this->user_id;
            $course->save();

            if ($session->locale) {
                if ($session->locale == 'ru_RU') {
                    $this->_helper->flashMessenger->addMessage(
                            '<li class="text-success">Курс добавлен успешно!</li>');
                } else {
                    $this->_helper->flashMessenger->addMessage(
                            '<li class="text-success">The course was successfully add!</li>');
                }
            }
            $this->_helper->redirector('index', 'courses');
        }

        $this->view->form = $form;
    }

    /**
     * Подписка на курс
     */
    public function subscribeAction() {

        $id = (int) $this->getRequest()->getParam('cid');
        $sid = (int) $this->getRequest()->getParam('sid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        $course = new Model_Course();
        $_row = $course->getCoursesById($id);
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->headTitle('Подписка на курс', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Страница подписки на курс.');
            } else {
                $this->view->headTitle('Subscription', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Subscription page.');
            }
        }

        $timeline = new Model_Subscribe();
        $this->isVisited = count($timeline->checkSubscribe($id, $this->user_id));

        if (!$this->isVisited) {
            foreach ($_row as $item) {
                if ($session->locale) {
                    if ($session->locale == 'ru_RU') {
                        $this->view->title = 'Вы подписаны на лекции курса ' . $item['name'];
                    } else {
                        $this->view->title = 'You are subscribed to the course  ' . $item['name'];
                    }
                }
            }
            $timeline->setSubscribe($id, $this->user_id);
        }
        else
            foreach ($_row as $item) {
                if ($session->locale) {
                    if ($session->locale == 'ru_RU') {
                        $this->view->title = 'Вы уже подписанны на лекции курса ' .
                                $item['name'];
                    } else {
                        $this->view->title = 'You are already subscribed at this course ' . $item['name'];
                    }
                }
            }

        $this->view->sid = $sid;
    }

    public function unsubscribeAction() {

        $id = (int) $this->getRequest()->getParam('cid');
        $sid = (int) $this->getRequest()->getParam('sid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');

        $course = new Model_Course();
        $_row = $course->getCoursesById($id);
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->headTitle('Отписка от курса', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Страница отписки на курс.');
            } else {
                $this->view->headTitle('Unsubscribe from the course', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Unsubscribe page.');
            }
        }
        $timeline = new Model_Subscribe();
        $this->isVisited = count($timeline->checkSubscribe($id, $this->user_id));

        if ($this->isVisited) {
            foreach ($_row as $item) {
                if ($session->locale) {
                    if ($session->locale == 'ru_RU') {
                        $this->view->title = 'Вы отписанны на лекции курса ' . $item['name'];
                    } else {
                        $this->view->title = 'Unsubscribe from course ' . $item['name'];
                    }
                }
            }
            $timeline->delSubscribe($id, $this->user_id);
        }
        else
            foreach ($_row as $item) {
                if ($session->locale) {
                    if ($session->locale == 'ru_RU') {
                        $this->view->title = 'Вы уже отписанны на лекции курса ' .
                                $item['name'];
                    } else {
                        $this->view->title = 'You already unsubscribe from course ' .
                                $item['name'];
                    }
                }
            }

        $this->view->sid = $sid;
    }

    public function editAction() {

        $id = (int) $this->getRequest()->getParam('cid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->view->headTitle('Редактирование курса', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Страница редактирования курса.');
            } else {
                $this->view->headTitle('Edit course', 'PREPEND');
                $this->view->headMeta()->appendName('description', 'Edit page of course.');
            }
        }


        // Проверка прав доступа
        $acl = Zend_Registry::get('acl');
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);
        $course = new Model_Course();
        $_row = $course->getCoursesById($id);
        foreach ($_row as $item) {
            $this->iddd = $item['course_id'];
            $this->iudd = $item['user_id'];
        }

        if (!isset($this->iddd)) {
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound', 'Error', false, array(null));
        }
        if ($this->user_id != $this->iudd) {
            if ($role != 'admin') {
                $this->getHelper('Redirector')->gotoSimpleAndExit('access', 'Error', false, array(null));
            }
        }
        if (!$acl->isAllowed($role, 'mvc:courses', 'edit'))
            return $this->_forward('login');

        // Используем форму
        $form = new Form_AddCourse();

        // Меняем action формы
        $form->setAction(Zend_Navigation_Page_Mvc::factory(array(
                    'action' => 'edit',
                    'controller' => 'courses'
                ))->getHref());
        // Меняем текст на кнопке submit
        $form->getElement('submit')->setLabel('Сохранить данные');
//        $form->addElement( 
//            'text', 'cid', array(
//            'label' => 'cid:', 
//            'filters' => array('Int') ));

        $cidp = new Zend_Form_Element_Hidden('cid');
        $cidp->addFilter('Int');

        $form->addElements(array($cidp));

        $cid = $this->getParam('cid');

        if (count($_POST)) {
            if ($form->isValid($_POST)) {
                $data = array(
                    'name' => $form->getValue('name'),
                    'subject_id' => $form->getValue('subject_id'),
                    'description' => $form->getValue('description')
                );

                //$this->view->password_confirm = $this->_request->getPost('password_confirm');
                //$form->getElement('email')->setValue($this->_request->getPost('password_confirm'));
                // Сохраняем изменения в БД
                Zend_Db_Table::getDefaultAdapter()->update(
                        TABLE_PREF . 'courses', $data, 'course_id=' . $cid);

                if ($session->locale) {
                    if ($session->locale == 'ru_RU') {
                        $this->_helper->FlashMessenger('<li class="text-success">Сохранено</li>');
                    } else {
                        $this->_helper->FlashMessenger('<li class="text-success">Saved</li>');
                    }
                }
                $this->_redirect($_SERVER['REQUEST_URI'] . '/cid/' .
                        $cid);
            }
        } else {
            // Вставляем в форму актуальные значения полей
            $course = new Model_Course();
            $_row = $course->getCoursesById($id);
            foreach ($_row as $item) {
                $form->setDefault('cid', $item['course_id']);
                $form->setDefault('name', $item['name']);
                $form->setDefault('subject_id', $item['subject_id']);
                $form->setDefault('description', $item['description']);
            }
        }

        //$this->view->user_id = $this->user_id;        
        $this->view->form = $form;
    }

    public function delAction() {
        $cid = (int) $this->getRequest()->getParam('cid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');

        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);
        $course = new Model_Course();
        $_row = $course->getCoursesById($cid);
        foreach ($_row as $item) {
            $this->iddd = $item['course_id'];
            $this->iudd = $item['user_id'];
        }

        if (!isset($this->iddd)) {
            $this->getHelper('Redirector')->gotoSimpleAndExit('nfound', 'Error', false, array(null));
        }
        if ($this->user_id != $this->iudd) {
            if ($role != 'admin') {
                $this->getHelper('Redirector')->gotoSimpleAndExit('access', 'Error', false, array(null));
            }
        }

        $lecture = new Model_Course();
        $lecture->delCourse($cid);

        if ($session->locale) {
            if ($session->locale == 'ru_RU') {
                $this->_helper->flashMessenger->addMessage(
                        '<li class="text-success">Курс удален!</li>');
            } else {
                $this->_helper->flashMessenger->addMessage(
                        '<li class="text-success">Course removed!</li>');
            }
        }
        if ($role != 'admin') {
            $this->getHelper('Redirector')->gotoSimpleAndExit('index', 'courses', false, array(null));
        } else {
            $this->_helper->redirector('courses', 'admin');
        }
    }

}